package com.example.demo.auth.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.auth.entity.LoginReq;
import com.example.demo.auth.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;

//  Login: '/auth/login',
//  Logout: '/auth/logout',
//  ForgePassword: '/auth/forge-password',
//  Register: '/auth/register',
//  twoStepCode: '/auth/2step-code',


@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {


    @PostMapping("/login")
    public Mono<JSONObject> login(@RequestBody LoginReq loginReq) throws FileNotFoundException {
        String username = loginReq.getUsername();
        String password = loginReq.getPassword();
        if ("admin".equals(username) && "admin".equals(password)){
            File file = ResourceUtils.getFile("/mock/user.json");
            JSONObject jsonObject = JSONUtil.readJSONObject(file, StandardCharsets.UTF_8);
            return Mono.just(jsonObject);
        }
        return Mono.empty();
    }
    @PostMapping("/logout")
    public Mono<ResponseEntity<Void>> logout() {
        log.info("[测试接口] 注销成功");
        return Mono.just(new ResponseEntity<Void>(HttpStatus.OK));
    }

    @PostMapping("/register")
    public Mono<ResponseEntity<Void>> register(@RequestBody Mono<User> loginResp) {
        return loginResp.mapNotNull(info -> {
            log.info("[测试接口] 注销成功");
            return new ResponseEntity<Void>(HttpStatus.OK);
        }).defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR));
    }
    @PostMapping("/forge-password")
    public Mono<ResponseEntity<Void>> forgePassword(@RequestBody Mono<User> loginResp) {
        return loginResp.mapNotNull(info -> {
            log.info("[测试接口] 注销成功");
            return new ResponseEntity<Void>(HttpStatus.OK);
        }).defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR));
    }
    @PostMapping("/2step-code")
    public Mono<Integer> stepCode() {
        log.info("[测试接口] 2step-code");
        return Mono.just(new Integer(1));
    }
}
